package com.example.spinnerdemo;

import com.example.spinnerdemo.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class ArrayAdapterForSpinnerWithImage extends ArrayAdapter<CharSequence> {

	private LayoutInflater mLayInfalter;
	private Spinner mSpinner;
	//ImageArray
	private TypedArray mTypedArray;
	
	public ArrayAdapterForSpinnerWithImage(Context context, int resource, CharSequence[] objects, Spinner spinner) {
		super(context, resource, objects);
		// TODO Auto-generated constructor stub
		
		mLayInfalter = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		mSpinner = spinner;
		
		//get ImageArray from resources
		mTypedArray = context.getResources().obtainTypedArray(R.array.Spinner_list_with_image);
		
	}

	@Override
	public View getDropDownView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		
		View v = mLayInfalter.inflate(R.layout.spinner_dropdown_item_with_image, parent, false);
		
		TextView txt = (TextView) v.findViewById(R.id.imgTxtSpinnerDropdown);
		txt.setText(getItem(position).toString());
		
		ImageView imgView = (ImageView) v.findViewById(R.id.imgSpinnerDropdown);
		imgView.setImageResource(mTypedArray.getResourceId(position, 0));
		
		if (position == mSpinner.getSelectedItemPosition())
			v.setBackgroundColor(Color.GRAY);
		
		return v;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		
		View v = mLayInfalter.inflate(R.layout.spinner_item_with_image, parent, false);
		
		TextView txt = (TextView) v.findViewById(R.id.imgTxtSpinner);
		txt.setText(getItem(position).toString());
		
		ImageView imgView = (ImageView) v.findViewById(R.id.imgSpinner);
		imgView.setImageResource(mTypedArray.getResourceId(position, 0));
		
		return v;
	}

}
